const db = require('./config/database')

async function testCreateUser () {
  try {
    console.log('🧪 测试创建用户功能...')

    // 测试数据
    const testUserData = {
      email: 'test' + Date.now() + '@example.com',
      nickname: '测试用户',
      password: 'test123',
      role: 'user',
      status: 'active',
      level: 1,
      balance: 0,
      avatar: null
    }

    console.log('📊 测试用户数据:', testUserData)

    // 检查必需的字段
    if (
      !testUserData.email ||
      !testUserData.nickname ||
      !testUserData.password
    ) {
      console.log('❌ 缺少必填字段')
      return
    }

    // 密码加密
    const bcrypt = require('bcrypt')
    const saltRounds = 10
    const passwordHash = await bcrypt.hash(testUserData.password, saltRounds)

    // 生成username
    const username = testUserData.nickname || testUserData.email.split('@')[0]

    // 处理VIP状态
    const isVip = false
    const vipExpireDate = null

    console.log('🔒 密码已加密，准备插入数据库...')

    // 创建用户
    const insertResult = await db.query(
      `
      INSERT INTO users (
        username, email, nickname, password_hash, role, status, level, 
        coins, is_vip, vip_expire_date, avatar_url, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
    `,
      [
        username,
        testUserData.email,
        testUserData.nickname,
        passwordHash,
        testUserData.role,
        testUserData.status,
        testUserData.level,
        testUserData.balance,
        isVip,
        vipExpireDate,
        testUserData.avatar
      ]
    )

    const userId = insertResult.insertId
    console.log('✅ 用户创建成功！用户ID:', userId)

    // 查询刚创建的用户
    const newUser = await db.query('SELECT * FROM users WHERE id = ?', [userId])
    console.log('📋 新创建的用户信息:', newUser[0])

    process.exit(0)
  } catch (error) {
    console.error('❌ 测试失败:', error)
    process.exit(1)
  }
}

testCreateUser()
